import { ref, type Ref, onMounted } from 'vue'
import type { IGoods, IBanner } from '@/types/types'

import { RequestBannerList,RequestGoodsList } from '@/api/goods'
import axios from 'axios'

/**
 * 轮播banner
 */
export const useBanner = ()=>{
    // 轮播列表
    const bannerList: Ref<Array<IBanner>> = ref([])
    // 获取轮播列表
    const getBannerList = async () => {
        const data = await RequestBannerList()
        const { resultCode, resultInfo } = data
        if (resultCode === 1) {
            bannerList.value = resultInfo.list
        }
    }
    onMounted(() => {
        getBannerList()
    })

    return { bannerList, getBannerList }
}

/**
 * 商品列表
 *   商品列表显示
 *   加载更多
 *   下拉刷新
 */
export const useGoods = (getBanner:Function)=>{
    // 加载数据状态，true表示加载中,false加载完成
    const loading: Ref<boolean> = ref(false)
    // 加载更新完成数据状态, 所有数据加载完成设置为true
    const finished: Ref<boolean> = ref(false)
    // 下拉刷新状态
    const refreshLoading: Ref<boolean> = ref(false)
    // 当前页号
    let currentNo = ref(1)
    // 商品列表
    const goodsList: Ref<Array<IGoods>> = ref([])
    // 获取商品列表
    const getGoodsList = async (currentNo: number) => {
    const data = await RequestGoodsList(currentNo, 15)

    const res = await axios({
        method: 'get',
        url: 'http://localhost:3000/goods/list',
        //post请求参数使用data选项, get参数 params选项
        params: {
            pageNum:currentNo,
            pageSize:15,
        }
    })
    // const { code, info } = res.data
    // console.log('code>>',code);
    // console.log('info>>',info);
    

    // 关闭下拉刷新, 手动下拉刷新时自动设置为true
    if (refreshLoading.value) {
        goodsList.value = []
        refreshLoading.value = false
    }

    const { code, info } = res.data
    if (code === 1) {
        goodsList.value = [...goodsList.value, ...info.list]
    }
    loading.value = false // loadding加载完成|关闭下拉刷新
    if (code === -1) {
        finished.value = true //所有数据加载完成
    }
    }
    /** 
     * 加载更多
     * 1.第一次进入自动调用,loading设置为true
     * 2.触底自动调用
     */
    const onLoad = () => {
        getGoodsList(currentNo.value++)
    }
    /**
     * 下拉刷新
     */
    const onRefresh = () => {
        // 重置
        currentNo.value = 1
        finished.value = false
        loading.value = false
        getGoodsList(currentNo.value)
        currentNo.value++
        getBanner()
    }
    return { goodsList, loading, finished, refreshLoading, onLoad, onRefresh }
}